var configFile = __dirname + '/config.json', // 配置文件
configFileCharset = "utf-8",

fs = require('fs'), // 引入 fs 文件读写模块
less = require('less'), // 引入 less 模块
path = require('path');

fs.readFile(configFile, configFileCharset, function(err, data) {
	var config = JSON.parse(data);
	var interval = config.interval || 500;
	var log = config.log || 'full';
	config.lesss.forEach(function(item) {
		var obj = path.parse(item);
		var watchLogStr;
		fs.watchFile(item, {
			interval : interval
		}, function(current, previous) {
			fs.readFile(item, 'utf-8', function(err, data) {
				less.render(data, function(err, css) {
					if (err) {
						logs(err);
					} else {
						var distPath = path.join(obj.dir, obj.name + ".css");
						fs.writeFile(distPath, css.css, function(err) {
							var outLogStr;
							if (err) {
								logs(err);
							} else {
								if (log === 'full') {
									outLogStr = distPath;
								} else {
									outLogStr = obj.name + ".css";
								}
								logs('输出：' + outLogStr);
							}
						});
					}
				});
			});
		});
		if (log === 'full') {
			watchLogStr = item;
		} else {
			watchLogStr = obj.name + obj.ext;
		}
		logs('启动监视：' + watchLogStr);
	});
});

function logs(str) {
	var now = new Date();
	var h = now.getHours();
	var m = now.getMinutes();
	var s = now.getSeconds();
	var S = now.getMilliseconds();
	if (h < 10) {
		h = "0" + h;
	}
	if (m < 10) {
		m = "0" + m;
	}
	if (h < 10) {
		h = "0" + h;
	}
	if (s < 10) {
		s = "0" + s;
	}
	if (S < 10) {
		S = "00" + S;
	} else if (S < 100) {
		S = "0" + S;
	}
	console.log("[" + h + ":" + m + ":" + s + "." + S + "] " + str);
}
